package com.hifar.test.equip.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hifar.common.QueryParamBean;
import com.hifar.fw.utils.lang.StringUtils;
import com.hifar.log.AutoLogUtils;
import com.hifar.plat.baseModal.pojo.BaseOssFiles;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.maindatasource.service.IMainDataSourceService;
import com.hifar.plat.officUtil.ExcelTemplateUtil;
import com.hifar.sys.*;
import com.hifar.test.equip.pojo.HfResEquip;
import com.hifar.test.equip.pojo.VO.*;
import com.hifar.test.equip.service.IHfResEquipService;
import com.hifar.test.equituit.pojo.HfResEquipUnit;
import com.hifar.test.equituit.service.IHfResEquipUnitService;
import com.hifar.test.unit.pojo.HfPrjUnitBase;
import com.hifar.test.unit.service.IHfPrjUnitBaseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 资源-设备 前端控制器 default
 * </p>
 *
 * @author wangkepeng
 * @since 2024-12-11 11:58:26
 */
@RestController
@RequestMapping("/api/busi/test/hfResEquipController")
@Api(tags = "资源-设备功能")
public class HfResEquipController {

    @Autowired
    private IHfResEquipService hfResEquipService;
    @Autowired
    private IHfResEquipUnitService equipUnitService;
    @Autowired
    private IHfPrjUnitBaseService unitBaseService;
    @Autowired
    private IBaseOssFilesService baseOssFilesService;

    @Autowired
    private IMainDataSourceService mainDataSourceService;

    @Autowired
    private AutoLogUtils autoLogUtils;

    @PostMapping(value = "/list")
    @ApiOperation(value = "资源-设备功能:分页查询列表")
    public BusiResponse list(@RequestBody @Validated HfResEquipQueryParamVO queryParamsVO) {
        QueryParamBean<HfResEquip> queryParamBean = new QueryParamBean<>(queryParamsVO);
        queryParamBean.addColumns(HfResEquip.class);
        QueryWrapper<HfResEquip> queryWrapper = queryParamBean.getQueryWrapper();
        Page<HfResEquip> page = queryParamBean.getPage();

        String searchType = StringUtils.trimNull(queryParamsVO.getSearchType(), "9");

        String equipTypeCode = StringUtils.trimNull(queryParamsVO.getEquipTypeCode(), "");
        if (!"".equals(equipTypeCode)) {
            queryWrapper.eq("equip_type_code", equipTypeCode);
        }
        String classifyTypeCode = StringUtils.trimNull(queryParamsVO.getClassifyTypeCode(), "");
        if (!"".equals(classifyTypeCode)) {
            queryWrapper.eq("classify_type_code", classifyTypeCode);
        }
        // 当天开始时间戳
        long tm = com.hifar.fw.utils.lang.DateUtils.getDayStartLong(System.currentTimeMillis());
        // 第8天开始
        long weekTime = tm + 7 * 24 * 60 * 60 * 1000L;
        // 第31天开始
        long monthTime = tm + 30 * 24 * 60 * 60 * 1000L;

        //1-过期数据 2-7天内过期 3-30天过期 4-有效设备 9-所有数据
        if ("9".equals(searchType)) {
        } else if ("1".equals(searchType)) {
            queryWrapper.gt("check_valid", new Date(0));
            queryWrapper.lt("check_valid", new Date(tm));
        } else if ("2".equals(searchType)) {
            queryWrapper.gt("check_valid", new Date(tm));
            queryWrapper.lt("check_valid", new Date(weekTime));
        } else if ("3".equals(searchType)) {
            queryWrapper.gt("check_valid", new Date(tm));
            queryWrapper.lt("check_valid", new Date(monthTime));
        } else if ("4".equals(searchType)) {
            queryWrapper.gt("check_valid", new Date(tm));
        }
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        queryWrapper.orderByAsc("row_sort");
        queryWrapper.orderByDesc("create_time");
        Page<HfResEquip> pageData = hfResEquipService.page(page, queryWrapper);

        List<HfResEquip> records = pageData.getRecords();

        List<String> ids = records.stream().map(HfResEquip::getId).collect(Collectors.toList());

        Map<String, List<BaseOssFiles>> imgFileMap = MinioUtil.getAttachInfoByRefType(ids, "hf_res_equip_img");

        records.forEach(item -> {
            List<BaseOssFiles> ossFiles = imgFileMap.get(item.getId());
            if (ossFiles != null) {
                item.setImgFileList(ossFiles);
            }
            if (ossFiles != null) {
                item.setAttachFileList(ossFiles);
            }
        });
        /*计算分页信息返回给前端*/
        PageResult pageResult = SystemUtil.parsePage(page, pageData);
        return BusiResponse.OK(pageResult);

    }

    @PostMapping(value = "/checkStatusCount")
    @ApiOperation(value = "资源-设备功能:统计鉴定有效状态")
    public BusiResponse countStatus(HttpServletRequest request) {

        QueryWrapper<HfResEquip> queryWrapper = new QueryWrapper<>();


        // 当天开始时间戳
        long tm = com.hifar.fw.utils.lang.DateUtils.getDayStartLong(System.currentTimeMillis());
        // 第8天开始
        long weekTime = tm + 7L * 24 * 60 * 60 * 1000;
        // 第31天开始
        long monthTime = tm + 30L * 24 * 60 * 60 * 1000;

        //1-过期数据 2-7天内过期 3-30天过期  4-有效设备  9-所有数据


        queryWrapper = new QueryWrapper<>();
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        int all = hfResEquipService.count(queryWrapper);

        queryWrapper = new QueryWrapper<>();
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        queryWrapper.gt("check_valid", new Date(0));
        queryWrapper.lt("check_valid", new Date(tm));
        int expire = hfResEquipService.count(queryWrapper);

        queryWrapper = new QueryWrapper<>();
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        queryWrapper.gt("check_valid", new Date(tm));
        int valid = hfResEquipService.count(queryWrapper);

        queryWrapper = new QueryWrapper<>();
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        queryWrapper.gt("check_valid", new Date(tm));
        queryWrapper.lt("check_valid", new Date(weekTime));
        int day7 = hfResEquipService.count(queryWrapper);

        queryWrapper = new QueryWrapper<>();
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);
        queryWrapper.gt("check_valid", new Date(tm));
        queryWrapper.lt("check_valid", new Date(monthTime));
        int day30 = hfResEquipService.count(queryWrapper);

        Map<String, Object> retMap = new HashMap<>();
        retMap.put("all", all);
        retMap.put("expire", expire);
        retMap.put("valid", valid);
        retMap.put("day7", day7);
        retMap.put("day30", day30);

        if (retMap != null) {
            return BusiResponse.OK(retMap);
        } else {
            return BusiResponse.ok("没有查询到数据！");
        }
    }

    @PostMapping(value = "/listAll")
    @ApiOperation(value = "资源-设备功能:查询列表(不带分页)")
    public BusiResponse listAll(@RequestBody @Validated HfResEquipQueryParamVO queryParamsVO) {
        QueryWrapper<HfResEquip> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("secret_level", SystemLoginUser.dataSecretSet);

        String equipTypeCode = StringUtils.trimNull(queryParamsVO.getEquipTypeCode(), "");
        if (!"".equals(equipTypeCode)) {
            queryWrapper.eq("equip_type_code", equipTypeCode);
        }
        queryWrapper.orderByAsc("row_sort");
        queryWrapper.orderByDesc("create_time");
        List<HfResEquip> list = hfResEquipService.list(queryWrapper);
        return BusiResponse.OK(list);
    }

    @PostMapping(value = "/add")
    @ApiOperation(value = "资源-设备功能:新增")
    public BusiResponse add(@RequestBody @Validated HfResEquipAddVO hfResEquipAddVO) {
        HfResEquip hfResEquip = new HfResEquip();
        BeanUtils.copyProperties(hfResEquipAddVO, hfResEquip);
        List<String> unitIdList = Optional.ofNullable(hfResEquipAddVO.getUnitIdList()).orElse(new ArrayList<>(0));
        //判断设备编号是否重复
        QueryWrapper<HfResEquip> queryWrapper = new QueryWrapper<>();
        String equipCode = hfResEquip.getEquipCode();
        queryWrapper.eq("equip_code", equipCode);
        int count = hfResEquipService.count(queryWrapper);
        if (count > 0) {
            return BusiResponse.error(400, String.format("设备编码%s已经存在！", hfResEquip.getEquipCode()));
        }
        hfResEquipService.save(hfResEquip);
        String id = hfResEquip.getId();

        List<BaseOssFiles> equipImagesList = Optional.ofNullable(hfResEquipAddVO.getEquipImages())
                .orElse(new ArrayList<>(0));
        List<BaseOssFiles> equipFileList = Optional.ofNullable(hfResEquipAddVO.getEquipFiles())
                .orElse(new ArrayList<>(0));
        for (BaseOssFiles baseOssFiles : equipImagesList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType("hf_res_equip_img");
        }
        for (BaseOssFiles baseOssFiles : equipFileList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType("hf_res_equip_attach");
        }

        UpdateWrapper<BaseOssFiles> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(BaseOssFiles::getRefId, null)
                .eq(BaseOssFiles::getRefId, id)
                .in(BaseOssFiles::getRefType, "hf_res_equip_img", "hf_res_equip_attach");
        baseOssFilesService.update(updateWrapper);
        baseOssFilesService.updateBatchById(equipFileList);
        baseOssFilesService.updateBatchById(equipImagesList);

        List<HfResEquipUnit> equipUnitList = new ArrayList<>(unitIdList.size());
        if (!unitIdList.isEmpty()) {
            List<HfPrjUnitBase> unitBaseList = unitBaseService.listByIds(unitIdList);
            for (int i = 0; i < unitBaseList.size(); i++) {
                HfPrjUnitBase hfPrjUnitBase = unitBaseList.get(i);
                HfResEquipUnit hfResEquipUnit = new HfResEquipUnit();
                hfResEquipUnit.setEquipId(id);
                hfResEquipUnit.setUnitId(hfPrjUnitBase.getId());
                hfResEquipUnit.setStatus("1");
                hfResEquipUnit.setRowSort(i);
                equipUnitList.add(hfResEquipUnit);
            }
            equipUnitService.saveBatch(equipUnitList);
        }

        autoLogUtils.addLog("环境试验-设备台账", String.format("新增设备:【%s】", equipCode));
        return BusiResponse.ok("添加成功");
    }

    @PostMapping(value = "/add2")
    @ApiOperation(value = "资源-设备功能:新增")
    public BusiResponse add2(@RequestBody String hfResEquip) {
        HfResEquip obj = com.alibaba.fastjson.JSON.parseObject(hfResEquip, HfResEquip.class);
        return BusiResponse.OK(obj);
    }


    @PostMapping(value = "/edit")
    @ApiOperation(value = "资源-设备功能:编辑")
    public BusiResponse edit(@RequestBody @Validated HfResEquipAddVO hfResEquipAddVO) {
        HfResEquip hfResEquip = new HfResEquip();
        BeanUtils.copyProperties(hfResEquipAddVO, hfResEquip);
        List<String> unitIdList = Optional.ofNullable(hfResEquipAddVO.getUnitIdList()).orElse(new ArrayList<>(0));
        //判断设备编号是否重复
        QueryWrapper<HfResEquip> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(HfResEquip::getEquipCode, hfResEquip.getEquipCode())
                .ne(HfResEquip::getId, hfResEquip.getId());


        int count = hfResEquipService.count(queryWrapper);
        if (count > 0) {
            return BusiResponse.error(400, String.format("设备编码%s已经存在！", hfResEquip.getEquipCode()));
        }

        Date checkValid = hfResEquip.getCheckValid();
        Date enableTime = hfResEquip.getEnableTime();
        Date startDate = hfResEquip.getStartDate();
        Date buyTime = hfResEquip.getBuyTime();
        Date checkTime = hfResEquip.getCheckTime();
        Date equipProducedDate = hfResEquip.getEquipProducedDate();
        Date maintainDate = hfResEquip.getMaintainDate();
        Date maintainValidDate = hfResEquip.getMaintainValidDate();

        Integer maintainPeriodValue = hfResEquip.getMaintainPeriodValue();
        String maintainPeriodUnit = hfResEquip.getMaintainPeriodUnit();

        Integer checkPeriodValue = hfResEquip.getCheckPeriodValue();
        String checkPeriodUnit = hfResEquip.getCheckPeriodUnit();
        String equipCode = hfResEquip.getEquipCode();
        hfResEquipService.updateById(hfResEquip);
        String id = hfResEquip.getId();

        UpdateWrapper<HfResEquip> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(HfResEquip::getCheckValid, checkValid == null ? null : checkValid)
                .set(HfResEquip::getEnableTime, enableTime == null ? null : enableTime)
                .set(HfResEquip::getStartDate, startDate == null ? null : startDate)
                .set(HfResEquip::getBuyTime, buyTime == null ? null : buyTime)
                .set(HfResEquip::getCheckTime, checkTime == null ? null : checkTime)
                .set(HfResEquip::getEquipProducedDate, equipProducedDate == null ? null : equipProducedDate)
                .set(HfResEquip::getMaintainDate, maintainDate == null ? null : maintainDate)
                .set(HfResEquip::getMaintainValidDate, maintainValidDate == null ? null : maintainValidDate)

                .set(HfResEquip::getCheckPeriodUnit, (checkPeriodValue == null || checkPeriodValue == 0) ? null : checkPeriodUnit)
                .set(HfResEquip::getMaintainPeriodUnit, (maintainPeriodValue == null || maintainPeriodValue == 0) ? null : maintainPeriodUnit)

                .set(HfResEquip::getUserDeptId, hfResEquip.getUserDeptId() == null ? null : hfResEquip.getUserDeptId())
                .set(HfResEquip::getUserDeptName, hfResEquip.getUserDeptName() == null ? null : hfResEquip.getUserDeptName())
                .in(HfResEquip::getId, id);
        hfResEquipService.update(updateWrapper);

        //保存图片
        List<BaseOssFiles> equipImagesList = Optional.ofNullable(hfResEquipAddVO.getEquipImages())
                .orElse(new ArrayList<>(0));
        List<BaseOssFiles> equipFileList = Optional.ofNullable(hfResEquipAddVO.getEquipFiles())
                .orElse(new ArrayList<>(0));
        for (BaseOssFiles baseOssFiles : equipImagesList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType("hf_res_equip_img");
        }
        for (BaseOssFiles baseOssFiles : equipFileList) {
            baseOssFiles.setRefId(id);
            baseOssFiles.setRefType("hf_res_equip_attach");
        }

        UpdateWrapper<BaseOssFiles> updateFileWrapper = new UpdateWrapper<>();
        updateFileWrapper.lambda()
                .set(BaseOssFiles::getRefId, null)
                .eq(BaseOssFiles::getRefId, id)
                .in(BaseOssFiles::getRefType, "hf_res_equip_img", "hf_res_equip_attach");
        baseOssFilesService.update(updateFileWrapper);
        baseOssFilesService.updateBatchById(equipFileList);
        baseOssFilesService.updateBatchById(equipImagesList);
        List<HfResEquipUnit> equipUnitList = new ArrayList<>(unitIdList.size());
        for (int i = 0; i < unitIdList.size(); i++) {
            String unitId = unitIdList.get(i);
            HfResEquipUnit hfResEquipUnit = new HfResEquipUnit();
            hfResEquipUnit.setEquipId(id);
            hfResEquipUnit.setUnitId(unitId);
            hfResEquipUnit.setStatus("1");
            hfResEquipUnit.setRowSort(i);
            equipUnitList.add(hfResEquipUnit);
        }
        equipUnitService.removeByEquipId(id);
        equipUnitService.saveBatch(equipUnitList);

        autoLogUtils.modifyLog("环境试验-设备台账", String.format("修改设备:【%s】", equipCode));
        return BusiResponse.ok("编辑成功！");
    }


    @GetMapping("/queryById")
    @ApiOperation(value = "资源-设备功能:根据id查询数据")
    public BusiResponse queryById(@RequestParam(name = "id") String id) {
        HfResEquip byId = hfResEquipService.getById(id);
        Assert.notNull(byId, "数据不存在!");
        HfResEquipVO hfResEquipVO = new HfResEquipVO();


        List<BaseOssFiles> imgFileList = MinioUtil.listByRefId(id, "hf_res_equip_img");
        byId.setImgFileList(imgFileList);


        List<BaseOssFiles> attachFilesList = MinioUtil.listByRefId(id, "hf_res_equip_attach");
        byId.setAttachFileList(attachFilesList);

        BeanUtils.copyProperties(byId, hfResEquipVO);
        List<ResEquipUnitVO> equipUnitList = equipUnitService.listByEquipId(id);
        hfResEquipVO.setEquipUnitList(equipUnitList);
        // 查询转换附件
        return BusiResponse.OK(hfResEquipVO);
    }

    @GetMapping("/queryHideColumns")
    @ApiOperation(value = "资源-设备功能:获取隐藏/显示字段")
    public BusiResponse queryHideColumns() {
        String selectSql = " select item_value as hide_columns from base_sys_switch where  " +
                " item_key='hf_res_equip_hide_columns' and status!=99 ";
        Map<String, Object> map = mainDataSourceService.selectOne(selectSql);
        return BusiResponse.OK(map);
    }


    @PostMapping("/editHideColumns")
    @ApiOperation(value = "资源-设备功能:更新隐藏/显示字段")
    public BusiResponse editHideColumns(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        String hideColumns = StringUtils.trimNull(pageInfo.get("hideColumns"));
        if (StringUtils.isNotEmpty(hideColumns)) {
            String updateSql = " update base_sys_switch set item_value='" + hideColumns + "' " +
                    "  where item_key='hf_res_equip_hide_columns' and status!=99 ";
            boolean update = mainDataSourceService.update(updateSql);
            return update ? BusiResponse.OK() : BusiResponse.error(400, "更新失败！");
        }
        return BusiResponse.error(400, "更新失败！");
    }


    @PostMapping("/delete")
    @ApiOperation(value = "资源-设备功能:逻辑删除")
    public BusiResponse delete(@RequestBody List<String> idList) {
        List<HfResEquip> equipList = hfResEquipService.listByIds(idList);
        hfResEquipService.removeByIds(idList);
        String equipNames = equipList.stream()
                .map(HfResEquip::getEquipCode)
                .distinct()
                .collect(Collectors.joining(","));
        autoLogUtils.deleteLog("环境试验-设备台账", String.format("删除了设备:【%s】", equipNames));
        return BusiResponse.ok("删除成功！");
    }

    @PostMapping("/exportExcel")
    @ApiOperation(value = "资源-设备功能:导出数据")
    public Object exportExcel(HttpServletRequest request) {
        Map<String, Object> pageInfo = RequestConver.getPageInfo(request);
        if (pageInfo == null) {
            return BusiResponse.error("参数有误！");
        }
        BusiResponse export = hfResEquipService.exportExcel(pageInfo);
        if (export.getCode() == com.hifar.fw.utils.bean.BusiConst.CODE_SUCCESS) {
            String encode = null;
            try {
                encode = URLEncoder.encode("设备基础信息.xlsx", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Type", "application/vnd.ms-excel");
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.add("Content-Disposition", "filename=" + encode);

            autoLogUtils.exportLog("环境试验-设备台账", "设备台账导出");
            return ResponseEntity.status(HttpStatus.OK).headers(headers).body((byte[]) export.getData());
        }
        return export;
    }

    @PostMapping("/importExcel")
    @ApiOperation(value = "资源-设备功能:导入excel数据")
    public BusiResponse importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return BusiResponse.error("文件为空！");
        } else {
            if (ExcelTemplateUtil.isExcelFile(file)) {
                autoLogUtils.importLog("环境试验-设备台账", "设备台账导入");
                return hfResEquipService.importExcel(file);
            } else {
                return BusiResponse.error("请上传excel文件！");
            }
        }
    }

}
